Repository navigation
feat(query): Add AND/OR condition grouping to QuerySelect and QueryDelete - #21
Merged
Merged
Conversation
…RE clause This commit introduces a convenience feature where the first logical operation (`AND` or `OR`) is automatically used as the `WHERE` clause if one is not explicitly set in the query builder. This simplifies query construction by removing the requirement to call `where()` first. The changes include: - Modifying the `build()` method in `QuerySelect.Builder` and `QueryDelete.Builder` to automatically identify and set the `WHERE` clause from the existing logical operations. - Updating `getSqlOperators()` in `QuerySelect`, `QueryDelete`, and `QueryUpdate` to correctly include the `where` operator in the returned list, improving query introspection.
This commit corrects a test case for `QueryDelete`. The test `build without where clause throws exception` was incorrectly including a WHERE condition, which prevented it from accurately verifying that building a `QueryDelete` without any conditions throws an `IllegalArgumentException`. The extraneous condition has been removed.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit modifies `QuerySelect` to support SQL queries without a `WHERE` clause. Previously, the `WHERE` clause was mandatory. This restriction has been lifted, but the requirement is maintained if other logical operations (like `AND` or `OR`) are present. The main changes include: - The `where` property in `QuerySelect` is now nullable (`SQLOperator<*>?`). - The `build()` method in the `QuerySelect.Builder` now only requires a `WHERE` clause if subsequent logical operations are added. - The SQL generation in `asSql()` has been updated to correctly build the `SELECT` statement when no `WHERE` clause is provided. - `getSqlOperators()` is updated to handle the nullable `where` property.
# Conflicts: # query/src/main/java/com/blipblipcode/query/QuerySelect.kt
Updates the Android Gradle Plugin version from 8.13.0 to 8.13.1.
feat(Query): Enhance `orderBy` and fix `like` operator
This commit introduces several improvements to the query builder, focusing on `ORDER BY` clause handling and correcting the behavior of the `like` operator.
Key changes include:
* **Fix `like` Operator Logic**: The `like()` method in `QuerySelect` and `QueryDelete` builders was incorrectly using a `LIKE` logical type. This has been corrected to use the `AND` logical type, ensuring it chains correctly with other conditions. The method signature is now restricted to `SQLOperator.Like`.
* **Enhanced `OrderBy` in Union and Join Queries**: `UnionQuery` and `InnerJoint` now correctly handle `ORDER BY` clauses. They aggregate `OrderBy` operators from all subqueries, clear them from the individual queries, and apply a combined `OrderBy` to the final result set. This prevents SQL errors and ensures predictable sorting. `QuerySelect` has been updated with `getOrderBy()` and nullable `orderBy()` methods to support this.
* **Improved `OrderBy` Implementation**:
* A new `OrderBy.Multiple` sealed class has been added to handle sorting by multiple columns with different sort directions.
* The `asSqlClause()` method was introduced for more flexible SQL string generation.
* **Extensive Testing**: Added comprehensive unit tests for the `orderBy` functionality in `QuerySelectTest`, covering various scenarios like single and multiple columns, mixed sort directions, aliases, and combinations with `LIMIT`.
This commit corrects the KDoc for the `orderBy` function in `UnionQuery`. The `@param` name has been updated from `columns` to `operator` to accurately match the function's parameter name.
This commit introduces support for case-insensitive comparisons in SQL operators by adding an optional `CaseConversion` parameter. This allows wrapping columns and values with `LOWER()` or `UPPER()` SQL functions.
The main changes include:
* **New `CaseConversion` Enum**: A new enum `CaseConversion` (`NONE`, `LOWER`, `UPPER`) has been created to specify the desired case conversion.
* **Updated `SQLOperator`**:
* The `SQLOperator` interface and all its implementing data classes now include a `caseConversion` property, which defaults to `NONE`.
* The `toSQLString()` methods have been updated to apply the corresponding SQL function (`LOWER()` or `UPPER()`) to both the column and the value when a conversion is specified.
* **New Test Cases**: Added tests to `QuerySelectTest` to verify the correct SQL generation for queries using `UPPER` case conversion in the `WHERE` clause.
This commit updates the following dependencies to their latest versions: * Kotlin: `2.0.21` -> `2.2.21` * AndroidX Lifecycle Runtime KTX: `2.9.4` -> `2.10.0` * AndroidX Activity Compose: `1.11.0` -> `1.12.1` * AndroidX Compose BOM: `2024.09.00` -> `2025.12.00` * AndroidX SQLite KTX: `2.6.1` -> `2.6.2`
This commit updates the Kotlin version badge in the `README.md` file. The version has been changed from `1.9+` to `2.2.21+` to reflect the current Kotlin version used in the project.
This commit refactors the `Field` data class to implement the `SQLOperator<T>` interface, standardizing its structure with other operators. The main changes include: - Implementing `SQLOperator` in `Field`, providing `symbol`, `column`, `value`, and `caseConversion` properties. - Updating the `asString()` method to use the newly added `symbol` property for SQL generation. - Adding a `clone()` method to the `OrderBy` sealed class and its subclasses (`Asc`, `Desc`, `Multiple`) to allow for deep cloning of instances, which improves immutability and flexibility in query construction. - Fixing the `IN` and `NOT IN` operators in `SQLOperator.kt` by ensuring that string values within the list are correctly quoted in the generated SQL.
This commit enhances the `Queryable` interface by adding a new overloaded `asSql` method. The new method accepts a predicate lambda, which allows for filtering the `SQLOperator`s that are included when generating the final SQL string. This provides more control and flexibility in SQL generation.
…nality
This commit introduces two main enhancements to the query builder classes: a new `asSql` method that accepts a predicate for filtering SQL operators, and a `clear` method for resetting query builders.
The key changes include:
* **Predicate-based `asSql(predicate)` Method**:
* All `Queryable` classes (`QuerySelect`, `QueryInsert`, `QueryUpdate`, `QueryDelete`, `UnionQuery`, `InnerJoint`) now implement an overloaded `asSql` method.
* This new method takes a predicate lambda, allowing for the conditional inclusion of SQL operators when generating the final SQL string.
* **`clear()` Method for Builders**:
* `QuerySelect` and `QueryDelete` (and their respective builders) now feature a `clear()` method.
* This method resets the query state by removing the `WHERE` clause and any subsequent logical operations (`AND`, `OR`), allowing builders to be reused for new queries.
This commit refactors `Limit`, `OrderBy`, `IsNull`, and `IsNotNull` to fully implement the `SQLOperator` interface. This standardization improves consistency across all SQL operators.
Key changes include:
* **`Limit` and `OrderBy` Implementation**:
* `Limit` and the sealed interface `OrderBy` (including `Asc`, `Desc`, and `Multiple`) now implement `SQLOperator`.
* They now define standard properties like `symbol`, `column`, `value`, and `caseConversion`.
* The `asString()` methods have been updated to use these properties for SQL generation.
* **`IsNull` and `IsNotNull` Adjustments**:
* The generic type for `IsNull` and `IsNotNull` has been changed from `Unit` to `String?`, with the `value` property now returning `null`.
* Their `toSQLString()` and `asString()` methods have been updated to support case conversion on the column.
This commit introduces `RepeatedQueryParameters`, a custom `LinkedHashMap` implementation designed to handle repeated query parameters in Retrofit. This utility class allows lists provided as values in a `@QueryMap` to be automatically expanded into multiple query parameters with the same key. This is useful for API endpoints that expect repeated keys, such as `?key=value1&key=value2`. Key features: - **`RepeatedQueryParameters` class**: Extends `LinkedHashMap` and overrides the `entries` property to transform list values into multiple `Map.Entry` objects. - **Factory methods**: Provides `create()`, `fromMap()`, and `empty()` for convenient instantiation. - **Handles lists**: Automatically expands `List<*>` values into separate key-value pairs. - **Null safety**: Throws exceptions for null keys and skips null values within lists.
This commit introduces a new extension function, `asQueryRepeatedQueryParameters`, for the `Queryable` interface. This function converts the SQL operators of a query into a `RepeatedQueryParameters` object, which is useful for integrations like Retrofit. Key features include: - A `predicate` parameter to conditionally filter which query parameters are included. - Support for regular parameters and repeated parameters (from `List` values). - Null-valued parameters are automatically excluded.
This commit enhances the `getSqlOperators()` method in `QuerySelect`. The `orderBy` and `limit` operators are now included in the returned list of SQL operators. This improves query introspection by providing a more complete representation of the query's components.
This commit introduces `RepeatedQueryParameters`, a utility class designed to bridge the gap between the `Query` library and Retrofit's `@QueryMap` annotation. It also adds a convenient extension function to convert `Queryable` objects directly into this new format.
The key changes include:
* **New `RepeatedQueryParameters` class**:
* This class extends `LinkedHashMap` and is designed to handle both single and repeated query parameters, which are common in REST APIs.
* It provides `addParameter()` for single values and `addRepeatedParameter()` for lists.
* A custom `entries` property expands list values into multiple `Map.Entry` objects, making it compatible with Retrofit's `@QueryMap` when used for repeated parameters (e.g., `?key=val1&key=val2`).
* **New `asQueryRepeatedQueryParameters()` extension function**:
* This function converts any `Queryable` object (like `QuerySelect`) into a `RepeatedQueryParameters` instance.
* It intelligently handles `SQLOperator` values, mapping single values directly and converting list-based operators (like `IN`) into repeated parameters.
* Operators with `Unit` or `null` values (e.g., `IsNull`) are automatically filtered out.
* An optional predicate allows for custom filtering of which operators are included.
* **Comprehensive Unit Tests**:
* Added `RepeatedQueryParametersTest.kt` to thoroughly validate the new class's behavior, including adding, overwriting, and expanding parameters.
* Added `QueryableRepeatedQueryParametersExtensionTest.kt` to test the conversion from `Queryable` to `RepeatedQueryParameters`, covering simple operators, list-based operators, and filtering logic.
This commit introduces `RepeatedQueryParameters`, a utility class designed to bridge the gap between the `Query` library and Retrofit's `@QueryMap` annotation. It also adds a convenient extension function to convert `Queryable` objects directly into this new format.
The key changes include:
* **New `RepeatedQueryParameters` class**:
* This class extends `LinkedHashMap` and is designed to handle both single and repeated query parameters, which are common in REST APIs.
* It provides `addParameter()` for single values and `addRepeatedParameter()` for lists.
* A custom `entries` property expands list values into multiple `Map.Entry` objects, making it compatible with Retrofit's `@QueryMap` when used for repeated parameters (e.g., `?key=val1&key=val2`).
* **New `asQueryRepeatedQueryParameters()` extension function**:
* This function converts any `Queryable` object (like `QuerySelect`) into a `RepeatedQueryParameters` instance.
* It intelligently handles `SQLOperator` values, mapping single values directly and converting list-based operators (like `IN`) into repeated parameters.
* Operators with `Unit` or `null` values (e.g., `IsNull`) are automatically filtered out.
* An optional predicate allows for custom filtering of which operators are included.
* **Comprehensive Unit Tests**:
* Added `RepeatedQueryParametersTest.kt` to thoroughly validate the new class's behavior, including adding, overwriting, and expanding parameters.
* Added `QueryableRepeatedQueryParametersExtensionTest.kt` to test the conversion from `Queryable` to `RepeatedQueryParameters`, covering simple operators, list-based operators, and filtering logic.
This commit enhances the KDoc for the `getOrderBy()` function in the `QuerySelect` builder. The new documentation clarifies that the function returns the `OrderBy` object for the query, or `null` if an `ORDER BY` clause has not been set.
This commit fixes a bug in the `Between` SQL operator where the start and end values were not being properly quoted in the generated SQL string. This could lead to SQL syntax errors when using string values. The `toSQLString()` and `asString()` methods in `SQLOperator.Between` have been updated to enclose the start and end values in single quotes.
feat(Query): Enhance `QuerySelect` and `UnionQuery` with builders and transformations
This commit introduces several improvements to the query building API, focusing on query mutability and builder reusability.
Key changes include:
* **Enhanced `QuerySelect`**:
* Added `newBuilder()` to create a builder from an existing query instance, facilitating query modification.
* Updated `where` clause storage to use a `Pair<String, SQLOperator<*>>` to support keyed identification of the primary condition.
* Added `getOperations()` to retrieve a map of all SQL operators (including WHERE) indexed by their keys.
* Introduced `transformOperation(key, transform)` in `QueryBuilder` to allow modifying specific logical operations by key.
* **Improved `UnionQuery`**:
* Renamed `UnionQuery.Builder` to `UnionQuery.QueryBuilder` for consistency.
* Added `newBuilder()` to allow extending or modifying existing union queries.
* Implemented `transformOperation(key, transform)` in the union builder, which applies the transformation recursively to all subqueries in the union.
* **Bug Fixes & Refactoring**:
* Corrected `QuerySelect` SQL generation to handle the updated `where` pair structure.
* Updated the `UnionQuery.addQuery` extension function to use the renamed `QueryBuilder`.
This commit cleans up the `UnionQuery.kt` file by removing several unused imports, including `QuerySelect.QueryBuilder`, `LogicalType`, and `kotlin.collections.set`.
…ethod from QuerySelect and UnionQuery
- Upgrades the Android Gradle Plugin (AGP) from version 8.13.2 to 9.0.0. - Updates the Gradle wrapper to version 9.3.1. - Removes the now-redundant `kotlin.android` plugin from build scripts, as it's included in AGP 9.0. - Adjusts build script structures to align with the new AGP version by moving the `kotlin` block. - Adds `limit` and `orderBy` to the operations map and exposes a `getLimit()` method in `QuerySelect`.
Updates several dependencies to their newer versions: - Kotlin from 2.2.21 to 2.3.10 - Activity Compose from 1.12.1 to 1.12.4 - Compose BOM from 2025.12.00 to 2026.02.00 Additionally, removes the unused `kotlin-android` plugin definition from the `[plugins]` section.
Updates several dependencies to their newer versions: - coreKtx from 1.17.0 to 1.18.0 - activityCompose from 1.12.4 to 1.13.0 - composeBom from 2026.02.00 to 2026.03.00
- Adds `getOperators()` to `QuerySelect` to retrieve a list of all `SQLOperator` instances from current operations. - Implements `clearOrderBy()` in both `QuerySelect` and `UnionQuery` to reset the `orderBy` field.
- Introduces a `Collation` sealed interface to handle SQL `COLLATE` clauses (e.g., `NOCASE`, `BINARY`, `RTRIM`) and custom collation names. - Updates `OrderBy.Asc` and `OrderBy.Desc` to support `collation` and a `transform` function for wrapping columns in SQL functions like `REPLACE`. - Adds `CollationUtils.removeCharsTransform()` to easily generate chained `REPLACE` calls for sanitizing sort keys. - Refactors `UnionQuery` to wrap internal queries in a subquery `SELECT * FROM (...)` when using `ORDER BY`, preventing syntax errors with combined results. - Updates `QuerySelect.asSql` to allow predicate filtering on `OrderBy` and `Limit` operations. - Adds comprehensive tests for collation, character removal transformations, and `UnionQuery` sorting behavior. - Updates documentation in `README.md` with examples for new sorting features.
…nQuery - Introduces `limit()` and `clearLimit()` to `UnionQuery` to apply or remove limit constraints across all internal queries. - Refactors `UnionQuery.asSql()` to ensure that a top-level `orderBy` takes precedence, ignoring internal query sort orders when set. - Adds `clearLimit()` to `QuerySelect` to allow resetting the `LIMIT` clause. - Implements `QuerySelectBuilder` test utility for more fluent test case construction. - Adds comprehensive unit tests for `limit` propagation and `orderBy` precedence within `UnionQuery`.
- Implements `toQueryDelete()` in `QuerySelect` to convert a select query into a delete query targeting the same table. - Ensures that `WHERE` and subsequent logical operations (`AND`/`OR`) are preserved during the conversion. - Adds a requirement for a `WHERE` clause to be present before conversion to prevent accidental full-table deletions. - Updates extension imports to support the new query conversion functionality.
# Conflicts: # query/build.gradle.kts # query/src/main/java/com/blipblipcode/query/QuerySelect.kt
- Introduces a `Copyable` interface to standardize deep cloning across SQL and logical operators. - Implements `clone()` in `SQLOperator` (Equals, NotEquals, Like, In, Between, etc.), `LogicalOperation`, `Field`, and `Limit` to ensure independent instances when modifying queries. - Refactors `OrderBy` cloning to use explicit `copy()` extension methods, simplifying the API and removing unsafe `vararg` parameters. - Fixes `QuerySelect.newBuilder()` to correctly clone the operations map, preventing unintended side effects on the original query. - Adds an `andNot(key, operator)` overload to `QuerySelect.QueryBuilder` for keyed logical operation management. - Implements comprehensive unit tests for query cloning, transformation, and state maintenance. - Standardizes test naming and structure following a new `TESTING_GUIDELINES.md` (snake_case, Given-When-Then, `runCatching` for exceptions). - Updates `Between` operator SQL generation to correctly handle string conversions and spacing.
…lOperation` and `OrderBy` - Renames `LogicalOperation.copy()` to `copyOperation()` and `OrderBy.copy()` to `copyOrderBy()` to avoid shadowing or conflicting with data class generated `copy` methods. - Fixes `copyOperation()` implementation for `Multiple` logical operations to correctly update the first operation in the list. - Fixes `copyOperation()` for all other `LogicalOperation` types by explicitly invoking constructors instead of relying on recursive `copy()` calls. - Updates `QuerySelectTest` and `CopyTest` to use the newly renamed extension methods. - Adds KDoc documentation to both extension methods to clarify their purpose and parameters.
- Updates Android Gradle Plugin (AGP) from 9.0.0 to 9.0.1.
- Sets the project version to `0.13.3` in the root `build.gradle.kts`.
- Introduces a comprehensive GitHub Actions release pipeline (`release-pipeline.yml`) triggered by Pull Requests to `master`.
- The new pipeline automates:
- Running unit tests for the `:query` module.
- Validating semantic versioning and ensuring the tag does not already exist.
- Building the release AAR artifact upon merging.
- Creating a GitHub Release with the attached AAR and a generated changelog.
- Monitoring the JitPack build status and logging.
- Posting a summarized status report as a comment on the PR.
- Updates various GitHub Actions to their latest versions (`checkout@v6`, `setup-java@v5`, `cache@v5`, `upload-artifact@v7`, `download-artifact@v8`, `action-gh-release@v3`, and `github-script@v9`). - Implements manual Gradle cache management in both `release-pipeline.yml` and `run-query-tests.yml`, including logic to detect and delete stale caches using the GitHub CLI (`gh cache delete`). - Adds a step to save the Gradle cache explicitly when a cache miss occurs. - Refines the `release-pipeline.yml` trigger to only run on `closed` pull request events. - Enhances `run-query-tests.yml` with concurrency controls, timeout limits, and a post-test cleanup of temporary Gradle files (lock files, daemon, etc.). - Standardizes unit test execution using optimized Gradle flags (`--parallel`, `--build-cache`, `--configuration-cache`) and improves the visibility of test results using `EnricoMi/publish-unit-test-result-action`. - Updates pipeline logging and messaging for better status reporting in CI logs.
- Updates various GitHub Actions to their latest versions (`checkout@v6`, `setup-java@v5`, `cache@v5`, `upload-artifact@v7`, `download-artifact@v8`, `action-gh-release@v3`, and `github-script@v9`). - Implements manual Gradle cache management in both `release-pipeline.yml` and `run-query-tests.yml`, including logic to detect and delete stale caches using the GitHub CLI (`gh cache delete`). - Adds a step to save the Gradle cache explicitly when a cache miss occurs. - Refines the `release-pipeline.yml` trigger to only run on `closed` pull request events. - Enhances `run-query-tests.yml` with concurrency controls, timeout limits, and a post-test cleanup of temporary Gradle files (lock files, daemon, etc.). - Standardizes unit test execution using optimized Gradle flags (`--parallel`, `--build-cache`, `--configuration-cache`) and improves the visibility of test results using `EnricoMi/publish-unit-test-result-action`. - Updates pipeline logging and messaging for better status reporting in CI logs.
This commit introduces a new `notify-discord` job to the GitHub Actions release pipeline. This job sends a detailed status report to a Discord webhook whenever a Pull Request is merged into the master branch. Key features of the notification include: - **Aggregated Pipeline Status**: Automatically determines the overall status (success, failure, cancelled, or skipped) based on the outcomes of preceding jobs (`check-tag`, `build-release`, `create-release`, and `jitpack-build`). - **Rich Embed Format**: Sends a Discord embed containing the library name, version, tag, branch, commit SHA, author, and event type. - **Dynamic Links**: Provides direct links to the specific GitHub Action run, the generated release/artifact, and the associated Pull Request. - **Robustness**: Uses `jq` for secure JSON payload construction and includes error handling for missing secrets or failed HTTP requests to the Discord API. - **Non-Blocking**: Configured with `continue-on-error: true` to ensure that notification failures do not impact the overall pipeline result.
# Conflicts: # .github/workflows/release-pipeline.yml # build.gradle.kts # query/src/main/java/com/blipblipcode/query/QuerySelect.kt # query/src/main/java/com/blipblipcode/query/operator/SQLOperator.kt # query/src/main/java/com/blipblipcode/query/utils/Extensions.kt
This commit updates the project version in `build.gradle.kts` from 0.13.4 to 0.13.5.
…eters
Retrofit validates the @QueryMap parameter by reading its generic
superclass via reflection. When R8 strips the Signature attribute, the
binding to LinkedHashMap<String, Any> is lost and consumers hit
@QueryMap keys must be of type String: K (parameter #2)
for method IMyApi.search
- Ship consumer-rules.pro with -keepattributes Signature and the matching
keep rule for RepeatedQueryParameters and $SimpleEntry.
- Promote the companion factories to @JvmStatic, expose a public no-arg
constructor and document the R8 contract on the class KDoc.
- Add unit tests covering the generic superclass, the static factory
surface and the no-arg constructor.
- Add an end-to-end R8 regression test that runs the real shrinker over
the class with the published rules and validates the resulting
signature plus a real Retrofit call through MockWebServer. It also
runs the same program without -keepattributes Signature to prove it
reproduces the bug.
- Document the R8 contract in the README.
Dependency bumps required by the new test stack and androidx.core 1.19.1:
AGP 9.0.1 -> 9.3.3, Kotlin 2.3.10 -> 2.4.20, androidx.core/appcompat/
material/sqlite/lifecycle/compose, compileSdk 36 -> 37, Gradle wrapper
9.3.1 -> 9.5.0.
…lete
Root cause: WHERE conditions were flattened with joinToString(" "), so an
OR appended to an AND chain was parsed by SQL as (a AND b) OR (...) instead
of a AND b AND (...). The library had no API to express the grouped intent.
- Fix: LogicalOperation.Multiple now renders its first condition with
toSQLString() (String values keep their quotes) and keeps the connector
of a nested group in position 0.
- Fix: Multiple rejects an empty operation list at construction time
instead of failing later in operations.first().
- New: Multiple.operators() exposes every operator in the group.
- New: andGroup()/orGroup() builders on QuerySelect and QueryDelete. The
group symbol decides how the group attaches to the chain; each grouped
condition keeps its own connector internally.
- New: QueryDelete.QueryBuilder.addLogicalOperation() for parity with
QuerySelect.QueryBuilder.
- Tests: LogicalGroupTest covers grouped AND/OR, nesting, quoting, empty
group rejection, predicate filtering, deep cloning and DELETE.
- Docs: README section + LOGICAL_GROUP_EXAMPLE.md.
- Version bumped to 0.14.0.
No breaking change: queries without groups render exactly as before.
…ngled Follow-up to the AND/OR grouping feature. The grouping primitive rendered and nested correctly, but everything around it still treated a group as a single operator, which produced invalid SQL or silent data loss. - Fix: asSql(predicate) now descends into groups via filterBy(). It used to filter on Multiple.operator, i.e. the first condition only, so rejecting one condition of a three-condition group dropped the whole group silently. A group that loses every condition is removed; when the WHERE clause does not survive, the first surviving condition is promoted to the WHERE position so the statement never starts with a dangling connector. - Fix: getSqlOperators()/getOperators() now return every operator of a group, including nested ones, so asQueryRepeatedQueryParameters() no longer serializes an N-condition group as a single parameter. - Fix: a group used as the WHERE clause emitted "WHERE AND (...)". Added asConditionString()/asWhereString() so any operation renders without its connector in anchor position; a group there emits "WHERE (a OR b)". - Fix: copyOperation replaced the first *element* of a group, nesting a group inside a group and emitting "AND (OR (a OR b))". It now replaces the first non-grouped condition, walking into nested groups. - Fix: toQueryDelete() unwrapped a grouped WHERE into its first operator, losing the group. QueryDelete.QueryBuilder gained where(key, operation). - Fix: Multiple accepted any string as connector and emitted it verbatim. It now rejects anything other than AND/OR at construction time. - Fix: operators() skipped nested groups, returning only the first operator of each nested level. - New: Multiple(vararg operations) constructor. - New: andGroup(key, connector, vararg conditions) / orGroup(key, connector, vararg conditions) on builders and instances, removing the need to wrap every condition in a LogicalOperation. - New: andGroup()/orGroup() on QuerySelect and QueryDelete instances, so a group can be added to an already built query. - Tests: 13 new cases covering all of the above. 228 tests green. No breaking change for queries without groups: flat rendering is untouched.
🚀 Release Pipeline — Resumen
📌 Versión nueva: 📥 Dependency (JitPack)// settings.gradle.kts
maven { url = uri("https://jitpack.io") }
// build.gradle.kts
implementation("com.github.LeandroLCD:android-sql-query:0.14.0")🤖 Generado automáticamente por el Release Pipeline · Run #7 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
tire_transfer_documentreturns rows that do not match the active filters because anORappended to aWHERE ... AND ...chain escapes the AND grouping. No issue key: reported directly on the downstream consumer app.QuerySelect/QueryDeleteflattened every WHERE condition into a single level withjoinToString(" "). SinceANDbinds tighter thanORin SQL,WHERE a AND b OR (c)is parsed as(a AND b) OR (c), so the filter columns no longer apply to the last terms. The library had no API to express the grouped intent, and the only grouping primitive,LogicalOperation.Multiple, rendered unquoted String values and dropped the connector of the first nested condition.Multiplehad no production call sites and no test coverage before this PR.andGroup()/orGroup()to express parenthesized groups, correctedMultiplerendering, and made the surrounding infrastructure (predicate filtering, operator extraction, WHERE anchoring, cloning) group-aware instead of treating a group as a single operator.Why each change
Multiple.asConditionString()instead ofoperator.asString()for the first condition: the old path skippedtoSQLString(), soStringvalues rendered asname = Adainstead ofname = 'Ada'.asConditionString()rather than being special-cased: a nested group in position 0 previously lost its connector, because the branch that emitssymbol + operandwas only applied to leaves.require(symbol in GROUP_CONNECTORS):symbolwas a freeString, soMultiple(listOf(...), "XOR")emittedXOR (a = 1)verbatim instead of failing.asConditionString()/asWhereString()on the interface: a group used as the WHERE clause emittedSELECT * FROM t AND (...), which is not valid SQL. Any operation now renders without its connector in anchor position, so a group there emitsWHERE (a OR b)and a promoted leaf emitsWHERE status = 'active'instead of a danglingAND.filterBy()recursing into groups:asSql(predicate)filtered onMultiple.operator, i.e. the first condition only, so rejecting one condition of a three-condition group dropped all three silently and produced a query missing filters the caller had not asked to remove.SELECT * FROM t AND x = 1.sqlOperators()recursing:getSqlOperators()returned one operator per group, soasQueryRepeatedQueryParameters()serialized an N-condition group as a single Retrofit@QueryMapentry.replaceFirstLeafOperator()incopyOperation: the old code replacedoperations[0], so a nested group was replaced by another group and renderedAND (OR (a OR b)). The replacement now walks into nested groups and targets the first non-grouped condition, keeping every connector intact.toQueryDelete()passing theLogicalOperationinstead of.operator: converting a query whose WHERE clause was a group silently dropped the group.andGroup(key, connector, vararg conditions)overload: thevararg LogicalOperationform requires repeatingLogicalOperation.Or(...)per condition, which is exactly the boilerplate the feature removes, andandGroup(..., Or(...), Or(...))reads as a contradiction.andGroup()/orGroup()on the instances:QuerySelectalready exposesaddLogicalOperation,remove,orderByandlimit, so requiringnewBuilder { }to add a group was an avoidable asymmetry.Platform
:query)Changes
query/src/main/java/com/blipblipcode/query/operator/LogicalOperation.kt—asConditionString(),asWhereString(),sqlOperators()andfilterBy()with defaults on the sealed interface;Multiplegained symbol validation, avarargconstructor, recursive operator traversal, and connector-preserving rendering; internallogicalGroup()/asLogicalOperation()helpers.query/src/main/java/com/blipblipcode/query/QuerySelect.kt—asSql(predicate)filters into groups and promotes the anchor;getSqlOperators()/getOperators()flatten;andGroup()/orGroup()(both overloads) on the builder and the instance;toQueryDelete()preserves a grouped WHERE.query/src/main/java/com/blipblipcode/query/QueryDelete.kt— sameasSql(predicate)andgetSqlOperators()treatment;addLogicalOperation(key, operation)andwhere(key, operation)on the builder;andGroup()/orGroup()on the builder and the instance.query/src/main/java/com/blipblipcode/query/utils/Extensions.kt—copyOperationreplaces the first non-grouped condition viareplaceFirstLeafOperator().query/src/test/java/com/blipblipcode/query/LogicalGroupTest.kt— new, 25 cases.query/src/test/java/com/blipblipcode/query/builder/QueryGroupBuilder.kt— new test builder.README.md— new "Agrupación de condiciones AND / OR" section, TOC entry, feature bullet.LOGICAL_GROUP_EXAMPLE.md— new feature doc.build.gradle.kts— version0.13.6→0.14.0(required by the release pipeline).Test Plan
copyOperationleaf replacement,toQueryDeletepreservation and instance-level grouping../gradlew :query:test→ 228 tests, 0 failures../gradlew :query:assembleRelease.Regression Risk
Multipleor thepredicateoverload, and both were invalid SQL or silent condition loss.asSql(predicate)now keeps the conditions a predicate accepts instead of dropping the whole group, andgetSqlOperators()now returns every operator of a group rather than the first, which changesasQueryRepeatedQueryParameters()output for queries that use groups. Flat rendering for queries without groups is untouched, so no previously generated SQL string changes.